package com.gw.vip.server.service.dao_service;

import com.gw.vip.common.exception.ServiceException;
import com.gw.vip.server.dao.HisTransMapper;
import com.gw.vip.server.dao.TransMapper;
import com.gw.vip.server.po.HisTrans;
import com.gw.vip.server.po.Trans;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author GW
 * @description
 * @since 2022-06-25
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class TransAllService {

    private final TransMapper transMapper;
    private final HisTransMapper hisTransMapper;

    /**
     * 根据 clientTransId 获取流水
     * @param clientTransId
     * @return
     */
    public Trans getByBase(String clientTransId){
        if (StringUtils.isBlank(clientTransId)){
            log.error("clientTransId 不可为空！");
            throw new ServiceException("clientTransId 不可为空！");
        }

        Trans trans = transMapper.getByBase(clientTransId);
        if (trans!=null){
            return trans;
        }

        HisTrans hisTrans = hisTransMapper.getByBase(clientTransId);
        if (hisTrans!=null){
            trans = new Trans();
            BeanUtils.copyProperties(hisTrans, trans);
            return trans;
        }

        return null;
    }

    public List<Trans> getByOrderId(String orderId){
        if (StringUtils.isBlank(orderId)){
            log.error("clientTransId 不可为空！");
            throw new ServiceException("clientTransId 不可为空！");
        }

        List<Trans> transList = transMapper.listByOrderId(orderId);
        if (transList.size()>0){
            return transList;
        }

        List<HisTrans> hisTransList = hisTransMapper.listByOrderId(orderId);
        if (hisTransList.size()>0){
            for (HisTrans hisTrans:hisTransList){
                Trans trans = new Trans();
                BeanUtils.copyProperties(hisTrans, trans);
                transList.add(trans);
            }
            return transList;
        }

        return null;
    }

    public boolean updateById(Trans trans) {
        int num = transMapper.updateById(trans);
        if (num>0){
            return true;
        }

        HisTrans hisTrans = new HisTrans();
        BeanUtils.copyProperties(trans, hisTrans);
        return hisTransMapper.updateById(hisTrans)>0;
    }
}
